<template>
  <div class="container">
    <!-- 商品分类面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 设置添加商品相关参数的说明 -->
      <el-alert
        title="设置添加商品相关参数的说明"
        type="warning"
        :closable="false"
        description
        show-icon>
        <template slot="" >
            <p>请先进行商品分类的选择，当所需三级商品分类被选中方可进行后续添加操作</p>
            <p>只允许为商品三级分类设置其动态参数和静态属性</p>
        </template>
      </el-alert>
      <!-- 级联选择器 -->
      <div class="block cascader-box">
          <el-tag type="success" class="cascader-title">
            请选择需要设置参数的三级分类品名
          </el-tag>
        <el-cascader
          v-model="selectNum"
          clearable
          ref="cascaderRef"
          @change="handleSelectChange"
          placeholder="请选择需要设置参数的三级分类商品名称..."
          :options="categoryListOptions"
          :props="cascaderProps"></el-cascader>
      </div>
      <!-- Tab栏目切换 -->
      <template>
        <el-tabs v-model="activeTab" type="card" @tab-click="handleClickSwitch">
          <el-tab-pane label="动态参数" :disabled="btnDisBool" name="many">
              <!-- 动态参数标签栏目 -->
              <span slot="label"><i class="el-icon-s-operation"></i>  品类动态可选参数</span>
              <!-- 增+动态参数按钮 -->
              <template>
                  <el-button class="btn-disable" type="primary" size="small" :disabled="btnDisBool" @click="handleAddManyParams">增加 动态可选参数 <i class="el-icon-circle-plus"></i></el-button>
              </template>
              <!-- 动态参数列表 -->
              <template>
                <el-table
                  :data="paramsData"
                  stripe
                  border
                  style="width: 100%">
                  <el-table-column type="index"></el-table-column>
                  <el-table-column type="expand">
                      <template slot-scope="scope">
                          <el-tag
                            :key="i"
                            v-for="(val, i) in scope.row.attr_vals"
                            closable
                            :disable-transitions="false"
                            @close="handleTagBtnClose(scope.row, i)">
                            {{val}}
                          </el-tag>
                          <el-input
                            class="input-new-tag"
                            v-if="scope.row.flag"
                            v-model="inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)">
                          </el-input>
                          <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 点击 新增{{scope.row.attr_name}}参数</el-button>
                      </template>
                  </el-table-column>
                  <el-table-column
                    prop="attr_name"
                    header-align="center"
                    label="商品动态参数名称列表">
                  </el-table-column>
                  <el-table-column
                    header-align="center"
                    align="center"
                    width="320px"
                    label="修改 / 删除 商品动态参数">
                    <template slot-scope="scop">
                      <el-button type="warning" class="btn-marginR" size="mini" icon="el-icon-edit" @click="handleeditAttrName(scop.row)">编辑</el-button>
                      <el-button type="danger" size="mini" icon="el-icon-delete"  @click="handleDelAttrName(scop.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
          </el-tab-pane>
          <el-tab-pane label="静态属性" :disabled="btnDisBool" name="only">
              <!-- 固定属性标签栏目 -->
              <span slot="label"><i class="el-icon-s-order"></i>  品类固定原始属性</span>
              <!-- 增删固定属性按钮 -->
              <template>
                <el-button  class="btn-disable" type="primary" size="small" :disabled="btnDisBool" @click="handleAddManyParams">增加 固定原始属性 <i class="el-icon-circle-plus"></i></el-button>
              </template>
              <!-- 固定属性列表 -->
              <template>
                <el-table
                  :data="paramsData"
                  stripe
                  border
                  style="width: 100%">
                  <el-table-column type="index"></el-table-column>
                  <el-table-column type="expand">
                    <template slot-scope="scope">
                      <el-tag
                        :key="i"
                        v-for="(val, i) in scope.row.attr_vals"
                        closable
                        :disable-transitions="false"
                        @close="handleTagBtnClose(scope.row, i)">
                        {{val}}
                      </el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="scope.row.flag"
                        v-model="inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)">
                      </el-input>
                      <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)"> + 点击 新增{{scope.row.attr_name}}参数 </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="attr_name"
                    header-align="center"
                    label="商品固定属性名称列表">
                  </el-table-column>
                  <el-table-column
                    header-align="center"
                    align="center"
                    width="320px"
                    label="修改 / 删除 商品固定属性">
                    <template slot-scope="scop">
                      <el-button type="warning" class="btn-marginR" size="mini" icon="el-icon-edit" @click="handleeditAttrName(scop.row)">编辑</el-button>
                      <el-button type="danger" size="mini" icon="el-icon-delete"   @click="handleDelAttrName(scop.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>

  <!-- 增加 动态/固定 属性对话框 -->
  <el-dialog :title="addAttrNameTitle" :visible.sync="addAttrNameParamsBool" @close="addAttrNameClose">
    <el-form :model="addAttrNameForm" label-position="right" ref="addAttrNameFormRef" label-width="145px" :rules="addAttrNameFormRules">
      <el-form-item :label="addAttrNameFormTitle" label-width="145px" prop="newAttrName">
      <el-input v-model="addAttrNameForm.newAttrName" :placeholder="addInputPlaceholder" autocomplete="off"></el-input>
    </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="addAttrNameParamsBool = false">取 消</el-button>
      <el-button type="primary" @click="addEditAttrNameSubmit">确 定</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GoodsParams',
  created () {
    // 获取初始化分类列表数据
    this.getCatrgoryList()
  },
  data () {
    // 验证编辑内容是否与服务器名称一致
    var isSameAttrName = (rule, value, callback, serverAttrName) => {
      if (value === serverAttrName) return callback(new Error('分类参数没有变化，请修改后进行提交！'))
      callback()
    }
    return {
      // 级联选择器初始数据
      categoryListOptions: [],
      // 级联选择器配置项
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 选中分类展示数据
      selectNum: [],
      // Tabs 选项卡激活选项
      activeTab: 'many',
      // 当前正在操作分类的id-value
      curCategoryId: 0,
      // 当前正在操作属性id-attrId
      curAttrParamsData: {},
      // 当前正在操作分类的name-label
      curCategoryName: '',
      // 动态/固定参数数据
      paramsData: [],
      // Tag标签input输入值
      inputValue: '',
      // input 数据绑定 新增动态/固定属性值
      addAttrNameForm: {
        newAttrName: ''
      },
      // 服务器保存原有的 AttrName
      serverAttrName: '',
      // 新增 动态/固定 属性对话框
      addAttrNameParamsBool: false,
      // 新增 动态/固定 input表单名称
      addAttrNameFormTitle: '',
      // 新增 动态/固定 input表单placeholder
      addInputPlaceholder: '',
      // 新增 动态/固定 验证规则
      addAttrNameFormRules: {
        newAttrName: [
          { required: true, message: '新增的参数名称必须填写...', trigger: 'blur' },
          { validator: (rule, value, callback) => { isSameAttrName(rule, value, callback, this.serverAttrName) }, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取分类级联列表分类数据
    async getCatrgoryList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryListOptions = res.data
    },
    // 三级分类选择变化处理函数
    handleSelectChange (selectNumArr) {
      this.paramsData = []
      if (selectNumArr.length !== 3) {
        this.$notify.warning({
          title: '商品分类层级选择提示',
          message: '管理员只允许设置三级分类相关参数！',
          offset: 200
        })
        return
      }
      const curentLabel = this.$refs.cascaderRef.getCheckedNodes()
      this.curCategoryName = curentLabel[0].label
      this.curCategoryId = selectNumArr[selectNumArr.length - 1]
      this.getParamsData(this.curCategoryId, this.activeTab)
    },
    // 切换选项卡Tab栏目
    handleClickSwitch (tabSelect) {
      if (this.selectNum.length !== 3) {
        this.paramsData = []
        return
      }
      this.activeTab = tabSelect.name
      this.getParamsData(this.curCategoryId, this.activeTab)
    },
    // 增加动态可选参数
    handleAddManyParams () {
      this.addAttrNameParamsBool = true
      this.serverAttrName = ''
      this.addAttrNameFormTitle = this.activeTab === 'many' ? '新动态参数名称' : '新固定属性名称'
      const attrSel = this.activeTab === 'many' ? '动态参数' : '固定属性'
      this.addInputPlaceholder = `请输入${this.curCategoryName}需要新增的${attrSel}名称...`
    },
    // 控制添加参数标签点击事件
    showInput (curParams) {
      curParams.flag = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // Tag标签失去焦点或按确认键即增加参数
    async handleInputConfirm (curParams) {
      if (this.inputValue.trim().length === 0) {
        curParams.flag = false
        return
      }
      // --------------------标签重复判断
      if (curParams.attr_vals.indexOf(this.inputValue) !== -1) return this.$message.warning(`${this.inputValue} 参数已经存在，请更改！`)
      curParams.attr_vals.push(this.inputValue)
      const attrValsStr = curParams.attr_vals.join(', ')
      const { data: res } = await this.$http.put(`categories/${this.curCategoryId}/attributes/${curParams.attr_id}`, {
        attr_name: curParams.attr_name,
        attr_sel: curParams.attr_sel,
        attr_vals: attrValsStr
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.inputValue = ''
      curParams.flag = false
      this.$message.success(res.meta.msg)
    },
    // Tag标签关闭即删除对应参数
    async handleTagBtnClose (curParams, index) {
      const attrID = curParams.attr_id
      const attrSel = curParams.attr_sel === 'only' ? '原始属性' : '可选参数'
      const attrName = curParams.attr_name
      const attrVal = curParams.attr_vals[index]
      const confirmRes = await this.$confirm(`确认删除${attrSel}中${attrName}的【${attrVal}】可选项吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info(`删除当前 ${attrSel}中${attrName}的【${attrVal}】选项操作被终止！`)
      const newAttrValArr = curParams.attr_vals.splice(index, 1)
      const newAttrValStr = newAttrValArr.join(', ')
      this.putAttrNameParamsData(this.curCategoryId, attrID, attrName, curParams.attr_sel, newAttrValStr)
    },
    // 新增/编辑 分类名称提交
    addEditAttrNameSubmit () {
      this.$refs.addAttrNameFormRef.validate(valid => {
        if (!valid) return this.$message.error('表单存在不合法信息,请根据提示检查更正!')
        if (this.serverAttrName) {
          this.putAttrNameParamsData(this.curCategoryId, this.curAttrParamsData.attr_id, this.addAttrNameForm.newAttrName, this.curAttrParamsData.attr_sel)
          this.getParamsData(this.curCategoryId, this.activeTab)
        } else {
          this.postParamsData(this.curCategoryId, this.addAttrNameForm.newAttrName, this.activeTab)
        }
      })
    },
    // 新增/编辑 分类名称窗口关闭
    addAttrNameClose () {
      this.$refs.addAttrNameFormRef.resetFields()
    },
    // 编辑 动态/静态 参数名称
    handleeditAttrName (currentAttr) {
      this.addAttrNameParamsBool = true
      this.addAttrNameFormTitle = this.activeTab === 'many' ? '修改动态参数名称' : '修改固定属性名称'
      this.addInputPlaceholder = `请修改原${currentAttr.attr_name}参数名称...`
      const promisCurrentAttr = this.getCurrentAttrParms(this.curCategoryId, currentAttr.attr_id, currentAttr.attr_sel)
      promisCurrentAttr.then(value => {
        this.curAttrParamsData = value
        this.serverAttrName = value.attr_name
        this.addAttrNameForm.newAttrName = value.attr_name
      })
    },
    // 删除 动态/静态 参数名称
    async handleDelAttrName (currentAttr) {
      if (!currentAttr) return this.$message.info('数据异常，请稍后重试！')
      const attrSel = currentAttr.attr_sel === 'only' ? '固定属性' : '动态参数'
      const attrName = currentAttr.attr_name
      const confirmRes = await this.$confirm(`确认删除${attrSel}中【${attrName}】选项吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info(`删除当前 ${attrSel}中【${attrName}】选项操作被终止！`)
      const { data: res } = await this.$http.delete(`categories/${this.curCategoryId}/attributes/${currentAttr.attr_id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getParamsData(this.curCategoryId, this.activeTab)
      this.$message.success(res.meta.msg)
    },
    // 【封装】根据ID查询参数GET-attr_id
    async getCurrentAttrParms (categoryID, attrID, dataType) {
      const { data: res } = await this.$http.get(`categories/${categoryID}/attributes/${attrID}`, { params: dataType })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      return res.data
    },
    // 【封装】添加动态参数或静态属性ajax请求数据POST-attr_name
    async postParamsData (categoryID, attrName, dataType) {
      const { data: res } = await this.$http.post(`categories/${categoryID}/attributes`, {
        attr_name: attrName,
        attr_sel: dataType
      })
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.addAttrNameParamsBool = false
      // console.log(res.data)
      // res.data.flag = false
      // res.data.attr_vals = res.data.attr_vals ? res.data.attr_vals.split(' ') : []
      // this.paramsData.push(res.data)
      // --------【nextTick【报错原因】 找不到flag属性，新返回的数据没有做相应处理】
      this.getParamsData(this.curCategoryId, this.activeTab)
      this.$message.success(res.meta.msg)
    },
    // 【封装】获取动态参数/静态属性ajax请求数据GET-categoryList
    async getParamsData (categoryID, dataType) {
      const { data: res } = await this.$http.get(`categories/${categoryID}/attributes`, { params: { sel: dataType } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      const paramsDataServe = res.data
      paramsDataServe.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.flag = false
      })
      this.paramsData = paramsDataServe
    },
    // 【封装】编辑分类名称，小标签参数增加、删除ajax请求PUT-attr_name
    async putAttrNameParamsData (curCategoryID, curAttrID, newAttrName, curAttrSel, curSetAttrVals) {
      const requestPutAttrName = { attr_name: newAttrName, attr_sel: curAttrSel }
      if (curSetAttrVals) { requestPutAttrName.attr_vals = curSetAttrVals }
      const { data: res } = await this.$http.put(`categories/${curCategoryID}/attributes/${curAttrID}`, requestPutAttrName)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.addAttrNameParamsBool = false
      if (this.serverAttrName) { this.getParamsData(this.curCategoryId, this.activeTab) }
      this.$message.success(res.meta.msg)
    }
  },
  computed: {
    // 计算属性控制添加按钮显示隐藏
    btnDisBool () {
      const isTureSelectArr = this.selectNum
      if (isTureSelectArr.length !== 3) return true
      return false
    },
    // 计算属性控制添加按钮标题的显示
    addAttrNameTitle () {
      let addAttrName = ''
      addAttrName = this.activeTab === 'many' ? '新增三级分类商品动态参数' : '新增三级分类商品固定属性'
      return addAttrName
    }
  }
}
</script>

<style lang="less" scoped>
// 面包屑导航
.el-breadcrumb {
    margin-bottom: 12px;
}
// 调整Alart提示信息p标签的内外间距
.el-alert {
    p {
        padding: 0;
        margin: 0;
    }
}
// 级联选择器样式调整
.cascader-box {
    margin: 20px 0;
    .cascader-title {
      margin-right: 12px;
      padding: 4px 10px;
      height: 40px;
      font-weight: 700;
    }
    .el-cascader {
        width: 400px;
    }
}
// 调整table表格index居中
/deep/ .el-table table tbody tr > td:first-child {
  text-align: center;
}
// 调整table表格expand居左
/deep/ .el-table .el-table__expanded-cell {
  text-align: left!important;
}
// Tabs栏目切换区域
.el-tabs {
    .btn-disable {
        margin: 8px 0 12px 0;
    }
    .el-table {
        .el-tag {
          margin-right: 10px;
          margin-bottom: 8px;
          text-align: center;
        }
        .button-new-tag {
          height: 32px;
          margin-left: 10px;
          line-height: 30px;
          padding-top: 0;
          padding-bottom: 0;
          color: #F56C6C;
          font-weight: 700;
        }
        .input-new-tag {
          width: 180px;
          margin-left: 10px;
          vertical-align: middle;
        }
    }
}

.btn-marginR {
  margin-right: 15px;
}
</style>
